package com.dy.placeOrder.web;

import com.alipay.api.AlipayApiException;
import com.alipay.api.internal.util.AlipaySignature;
import com.dy.placeOrder.ConfirmOrder;
import com.dy.placeOrder.service.ConfirmOrderService;
import com.dy.placeOrder.zhifubao.AppUtil;
import com.dy.placeOrder2.service.OrdersService;
import com.dy.pojo.Orders;
import com.dy.user.User;
import com.dy.user.service.IUserService;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.PrintWriter;
import java.math.BigDecimal;
import java.util.HashMap;
import java.util.Iterator;
import java.util.Map;

@Controller
public class ReturnController {

    @Resource
    private ConfirmOrderService confirmOrderService;
    @Resource
    private OrdersService ordersService;
    @Resource
    private IUserService userService;

    @Resource
    private RedisTemplate redisTemplate;

    @RequestMapping("/getreturn")
    public void getreturn(HttpServletRequest request, HttpServletResponse response) throws AlipayApiException, IOException {
        System.out.println("getreturn111111111");
        //获取支付宝GET过来反馈信息
        Map<String,String> params = new HashMap<String,String>();
        // 其他参数
        Map<String,String[]> requestParams = request.getParameterMap();
        Iterator<String> iter = requestParams.keySet().iterator();
        while(iter.hasNext()){
            String name = (String) iter.next();
            String[] values = (String[]) requestParams.get(name);
            String valueStr = "";
            for (int i = 0; i < values.length; i++) {
                valueStr = (i == values.length - 1) ? valueStr + values[i]
                        : valueStr + values[i] + ",";
            }
            //乱码解决，这段代码在出现乱码时使用
            //valueStr = new String(valueStr.getBytes("ISO-8859-1"), "utf-8");
            params.put(name, valueStr);
        }

        //RSA2验证
        boolean signVerified = AlipaySignature.rsaCheckV2(params, AppUtil.alipay_public_key, AppUtil.charset, AppUtil.sign_type); //调用SDK验证签名
        response.setContentType("text/html;charset=utf-8");
        PrintWriter out = response.getWriter();
        //——请在这里编写您的程序（以下代码仅作参考）——
        if(signVerified) {
            //商户订单号
            String out_trade_no = request.getParameter("out_trade_no");
            //支付宝交易号
            String trade_no = request.getParameter("trade_no");
            //付款金额
            String total_amount = request.getParameter("total_amount");
            out.println("trade_no:"+trade_no+"<br/>out_trade_no:"+out_trade_no+"<br/>total_amount:"+total_amount);
            response.sendRedirect("http://localhost:8080/#/Payment_results");
        }else {
            Integer cid =(Integer) redisTemplate.opsForValue().get("cid");
            ConfirmOrder byId = confirmOrderService.getById(cid);
            byId.setState(2);
            confirmOrderService.updateById(byId);

            User byId1 = userService.getById(byId.getUid());
            //充值余额时，进入此处
            if (byId.getOid()==null || byId.getRid()==null) {

                if (byId1.getDoucoin() == null) {
                    byId1.setDoucoin(BigDecimal.ZERO);
                }

                BigDecimal currentDoucoin = byId1.getDoucoin();
                BigDecimal totalAmount = byId.getTotalAmount();

                // 执行加法运算
                BigDecimal newDoucoin = currentDoucoin.add(totalAmount);

                // 保留为 Integer，确保范围合适
                byId1.setDoucoin(newDoucoin);

                System.out.println("抖币支付成功，用户抖币增加" + byId1.getDoucoin());

                userService.updateById(byId1);

                response.sendRedirect("http://localhost:8080/#/wallet");

            }else {
                Orders orders = ordersService.getById(byId.getOid());
                orders.setStatus("待发货");
                ordersService.updateById(orders);

                // 积分为null时，初始化为0
                if (byId1.getIntegral() == null){
                    byId1.setIntegral(0);
                }

                //花费一元，赠送100积分
                int jf = byId.getTotalAmount().multiply(BigDecimal.valueOf(100)).intValue();
                byId1.setIntegral(byId1.getIntegral() +jf);
                userService.updateById(byId1);

                response.sendRedirect("http://localhost:8080/#/Payment_results");
            }


//            out.println("验签失败");
        }
    }
}
